package com.qf.shop.auth.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

@Component
public class FeignHeadInterceptor implements RequestInterceptor {

    /**
     * @param requestTemplate feign调用时新创建的请求对象
     */
    @Override
    public void apply(RequestTemplate requestTemplate) {
        requestTemplate.header("name", "value");

        // 1.获取HttpServletRequset对象
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();

        // 2.从req对象中获取请你头
        Enumeration<String> headerNames = request.getHeaderNames();

        // 3.遍历
        while (headerNames.hasMoreElements()) {
            String key = headerNames.nextElement();
            String value = request.getHeader(key);

            // 3.全部放到新的请求头中
            requestTemplate.header(key, value);
        }


    }
}
